package com.fafa.swing.base;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/**
 * @author : fafa
 * @version V1.0
 * @Project: SwingTest
 * @Package com.fafa.swing
 * @Description: SelectListSampleDemo
 * @date Date : 2019年11月24日 20:30
 */
public class SelectListSampleDemo extends JFrame {

    private JPanel panel = new JPanel();
    private JComboBox cmb = new JComboBox();
    private JLabel label = new JLabel("添加新星座：");
    private JLabel showInfo = new JLabel(); //用于显示信息
    private JTextField jtf = new JTextField(16);
    private JButton buttonAdd = new JButton("新增");
    private JButton buttonDel = new JButton("删除");

    public SelectListSampleDemo(){
        JFrame jFrame = new JFrame("选择你的星座");
        cmb.addItem("---请选择---");
        cmb.addItem("巨蟹座");
        cmb.addItem("狮子座");
        cmb.addItem("双鱼座");
        panel.add(cmb);
        panel.add(label);
        panel.add(jtf);
        panel.add(buttonAdd);
        panel.add(buttonDel);

        buttonAdd.addActionListener(new MyActionListener());
        buttonDel.addActionListener(new MyActionListener());
        cmb.addItemListener(new MyItemListener());

        jFrame.add(panel);
        jFrame.setBounds(300,200,600,400);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }

    class MyItemListener implements ItemListener{

        @Override
        public void itemStateChanged(ItemEvent e) {
            String str = e.getItem().toString();
            panel.add(showInfo);
            showInfo.setText("您选择的星座是: "+str);
        }
    }

    //添加新增和删除按钮的监听事件
    private class MyActionListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            //添加按钮处理
            if (command.equals("新增")){
                if(jtf.getText().length() != 0){
                    cmb.addItem(jtf.getText());
                    panel.add(showInfo);
                    showInfo.setText("添加成功，新增了："+jtf.getText());
                }else{
                    panel.add(showInfo);
                    showInfo.setText("请输入要添加的星座");
                }
            }

            //删除按钮处理
            if(command.equals("删除")){
                if(cmb.getSelectedIndex() != -1){
                    //先获得要删除的项的值
                    String strDel = cmb.getSelectedItem().toString();
                    cmb.removeItem(strDel);
                    showInfo.setText("删除成功，删除了："+strDel);
                    panel.add(showInfo);
                }else{
                    showInfo.setText("请选择要删除的星座");
                    panel.add(showInfo);

                }
            }
        }
    }


    public static void main(String[] args) {
        new SelectListSampleDemo();
    }
}
